package com.magicalcoder.youyamvc.web.controller.admin.goods;
import com.magicalcoder.youyamvc.app.goods.service.GoodsService;
import com.magicalcoder.youyamvc.app.goods.service.GoodsProxyService;
import com.magicalcoder.youyamvc.app.goods.constant.GoodsConstant;
import com.magicalcoder.youyamvc.app.goods.util.GoodsUtil;
import com.magicalcoder.youyamvc.app.goods.dto.GoodsDto;
import com.magicalcoder.youyamvc.app.model.Goods;
import com.magicalcoder.youyamvc.app.model.Priority;
import com.magicalcoder.youyamvc.core.common.utils.POIUtil;
import com.magicalcoder.youyamvc.core.common.utils.ProjectUtil;
import com.magicalcoder.youyamvc.core.common.utils.ListUtils;
import com.magicalcoder.youyamvc.core.common.utils.StringUtils;
import com.magicalcoder.youyamvc.core.common.dto.AjaxData;
import com.magicalcoder.youyamvc.core.common.utils.copy.Copyer;
import com.magicalcoder.youyamvc.core.spring.admin.AdminLoginController;
import com.magicalcoder.youyamvc.core.common.dto.InputSelectShowDto;
import com.magicalcoder.youyamvc.app.adminuser.util.AdminUserContextUtil;
import com.magicalcoder.youyamvc.app.goodsimg.service.GoodsImgService;
import com.magicalcoder.youyamvc.app.model.GoodsImg;
import java.io.File;
import java.io.IOException;
import com.alibaba.fastjson.JSON;
import com.magicalcoder.youyamvc.core.common.file.FileHelper;
import com.magicalcoder.youyamvc.core.common.utils.copy.Copyer;
import com.magicalcoder.youyamvc.core.common.utils.serialize.SerializerFastJsonUtil;
import com.magicalcoder.youyamvc.core.spring.admin.AdminLoginController;
import org.springframework.web.multipart.MultipartFile;
import com.magicalcoder.youyamvc.core.common.exception.BusinessException;

import org.springframework.format.annotation.DateTimeFormat;
import java.util.*;
import java.math.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;

/**
* 代码为自动生成 Created by www.magicalcoder.com
* 如果你改变了此类 read 请将此行删除
*  欢迎加入官方QQ群:323237052
*/

@RequestMapping({"/admin/goods"})
@Controller
public class AdminGoodsListController extends AdminLoginController
{
    private final String moduleName = "goods";

    @Resource
    private GoodsImgService goodsImgService;


    @Resource
    private GoodsService goodsService;
    @Resource
    private GoodsProxyService goodsProxyService;
    //列表页
    @RequestMapping(value={"list"}, method={RequestMethod.GET})
    public String list(ModelMap model,
        HttpServletRequest request, HttpServletResponse response)
    {
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanQuery()){
            return "admin/priorityAlert";
        }
        Goods goods = new Goods();
        return "admin/goods/goodsList";
    }

    //分页查询
    @RequestMapping(value={"page/{pageIndex}/{pageSize}/{pageCount}"}, method={RequestMethod.GET})
    public void page(@PathVariable Integer pageIndex,@PathVariable Integer pageSize, @PathVariable Integer pageCount,
        @RequestParam(required=false, value="orderBySqlField") String orderBySqlField,
        @RequestParam(required=false, value="descAsc") String descAsc,
        @RequestParam(required = false,value ="goodsNameFirst")                        String goodsNameFirst ,
        @RequestParam(required = false,value ="createTimeFirst")                    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date createTimeFirst ,
        @RequestParam(required = false,value ="createTimeSecond")                    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date createTimeSecond ,
        @RequestParam(required = false,value ="publisStatusFirst")                        Boolean publisStatusFirst ,
        HttpServletRequest request, HttpServletResponse response)
    {
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanQuery()){
            toWebFailureJson(response,"权限不足");
            return;
        }
        String orderBySqlFieldStr = ",id,goods_name,create_time,publis_status,";
        String orderBy = ProjectUtil.filterOrderBy(orderBySqlFieldStr,orderBySqlField,descAsc);
        if(StringUtils.isBlank(orderBy)){
                orderBy = "";
        }
        pageSize = Math.min(GoodsConstant.PAGE_MAX_SIZE,pageSize);
        int idx = (pageIndex.intValue() - 1) * pageSize;

        Map<String,Object> query = ProjectUtil.buildMap("orderBy", orderBy, new Object[] {
                "goodsNameFirst",goodsNameFirst ,
                "createTimeFirst",createTimeFirst ,
                "createTimeSecond",createTimeSecond ,
                "publisStatusFirst",publisStatusFirst ,
        "limitIndex",idx,"limit", pageSize });

        boolean useRelateQuery = false;
        List pageList;
        pageList = this.goodsService.getGoodsList(query);
        query.remove("orderBy");
        query.remove("limitIndex");
        query.remove("limit");
        if (pageCount == null || pageCount.intValue() == 0) {
                pageCount = this.goodsService.getGoodsListCount(query);
        }

        Map ajaxData = new HashMap();
        ajaxData.put("pageList", dealForeignField(pageList));
        ajaxData.put("pageCount", pageCount);
        toWebSuccessJson(response, ajaxData);
    }

//处理外键显示字段 而不是难读懂的关联字段
    private List<Map<String,Object>> dealForeignField(List<Goods> pageList){
        List<Map<String,Object>> newPageList = new ArrayList<Map<String, Object>>(pageList.size());
        if(ListUtils.isNotBlank(pageList)){
        //step1 转化map快速索引




            //使用索引替换外键展示值
            for(Goods item:pageList){
                String json = JSON.toJSONString(item);
                Map<String,Object> obj = (Map<String,Object>)JSON.parse(json);
                obj.put("createTime",item.getCreateTime());
                newPageList.add(obj);
            }
        }
        return newPageList;
    }
    //根据自定义查询条件到编辑
    @RequestMapping({"/detail_param"})
    public String detailId(HttpServletRequest request,ModelMap model) {
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanQuery()){
            return "admin/priorityAlert";
        }
        Map<String,Object> reqMap = ProjectUtil.getParams(request);
        Goods entity = this.goodsService.selectOneGoodsWillThrowException(reqMap);
        model.addAttribute("goods", entity);
        foreignModel(entity,model);
        return "admin/goods/goodsDetailRelate";
    }
    //新增
    @RequestMapping({"/detail"})
    public String detail( HttpServletRequest request,
        ModelMap model) {
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanInsert()){
            return "admin/priorityAlert";
        }
        Goods goods = new Goods();
        foreignModel(goods,model);
        model.addAttribute("goods", goods);
        return "admin/goods/goodsDetailRelate";
    }

    private void foreignModel(Goods entity,ModelMap model){
        Map<String,Object> map;
        if(entity.getId()!=null){
            List<GoodsImg> goodsImgList = null;
            goodsImgList = goodsImgService.getGoodsImgList(ProjectUtil.buildMap("goodsId",entity.getId(),"limitIndex",0,"limit",100));
            model.addAttribute("goodsImgList",goodsImgList);
        }

    }


    //根据主键到编辑
    @RequestMapping({"/detail/{id}"})
        public String detailId(@PathVariable Long id,
        HttpServletRequest request,ModelMap model) {
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanQuery()){
            return "admin/priorityAlert";
        }
        Goods entity = this.goodsService.getGoods(id);
        model.addAttribute("goods", entity);
        foreignModel(entity,model);
        return "admin/goods/goodsDetailRelate";
    }

    //ajax更新状态
    @RequestMapping(value="ajax_update", method={RequestMethod.POST})
    public void ajaxUpdate(@ModelAttribute Goods goods,
        HttpServletRequest request,HttpServletResponse response,ModelMap model) {
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanUpdate()){
            toWebFailureJson(response,"权限不足");
            return;
        }
        try{
            this.goodsService.updateGoodsWithoutNull(goods);
            toWebSuccessJson(response);
        }catch (Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            model.addAttribute("exceptionMsg","保存失败："+exceptionMsg);
            toWebFailureJson(response,exceptionMsg);
        }
    }
    //保存
    @RequestMapping(value="save", method={RequestMethod.POST})
    public String save(@ModelAttribute Goods goods,
        HttpServletRequest request,ModelMap model) {
        try{
            model.addAttribute("goods",goods);
            foreignModel(goods,model);
            Date now = new Date();
            if (goods.getId() == null) {
                Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
                if(adminQueryPriority==null || !adminQueryPriority.getCanInsert()){
                    return "admin/priorityAlert";
                }
                        goods.setCreateTime(now);
                this.goodsService.insertGoods(goods);
            } else {
                Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
                if(adminQueryPriority==null || !adminQueryPriority.getCanUpdate()){
                    return "admin/priorityAlert";
                }
                Goods entity = this.goodsService.getGoods(goods.getId());
                        goods.setCreateTime(entity.getCreateTime());
                Copyer.copy(goods, entity);
                this.goodsService.updateGoods(entity);
            }
        }catch (Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            model.addAttribute("exceptionMsg","保存失败："+exceptionMsg);
            return "admin/goods/goodsDetailRelate";
        }
        return "redirect:/admin/goods/list";
    }

    //ajax保存
    @RequestMapping(value="ajax_save", method={RequestMethod.POST})
    public void save(@ModelAttribute Goods goods,
        HttpServletRequest request,HttpServletResponse response,ModelMap model) {
        Long id = goods.getId();
        try{
            foreignModel(goods,model);
            Date now = new Date();
            if (goods.getId() == null) {
                Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
                if(adminQueryPriority==null || !adminQueryPriority.getCanInsert()){
                    toWebFailureJson(response,"goods无插入数据权限");
                    return;
                }
                        goods.setCreateTime(now);
                id = this.goodsService.insertGoods(goods);
            } else {
                Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
                if(adminQueryPriority==null || !adminQueryPriority.getCanUpdate()){
                    toWebFailureJson(response,"goods无更新数据权限");
                    return;
                }
                Goods entity = this.goodsService.getGoods(goods.getId());
                        goods.setCreateTime(entity.getCreateTime());
                Copyer.copy(goods, entity);
                this.goodsService.updateGoods(entity);
            }
        }catch (Exception e){
            String exceptionMsg = ProjectUtil.buildExceptionMsg(e.getMessage());
            toWebExceptionJson(response,"保存失败："+exceptionMsg);
            return;
        }
        toWebSuccessJson(response,id,false);
    }

    //ajax批量保存
    @RequestMapping(value="batch_save", method={RequestMethod.POST})
    public void save(@RequestParam String saveJson,
        HttpServletResponse response,HttpServletRequest request,ModelMap model) {                  
        List<Goods> goodsList = SerializerFastJsonUtil.get().readJsonList(saveJson,Goods.class);
        List<Goods> insert = new ArrayList<Goods>();
        List<Goods> update = new ArrayList<Goods>();
        for(Goods goods:goodsList){
            
            if(goods.getId()==null){
                insert.add(goods);
            }else {
                update.add(goods);
            }
        }
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        String priority = "";
        if(ListUtils.isNotBlank(insert)){
            if(adminQueryPriority==null || !adminQueryPriority.getCanInsert()){
                priority = "goods无插入数据权限";
            }else {
                goodsService.batchInsertGoods(insert);
            }
        }
        if(ListUtils.isNotBlank(update)){
            if(adminQueryPriority==null || !adminQueryPriority.getCanUpdate()){
                priority += "goods无更新数据权限";
            }else {
                goodsService.batchUpdateGoods(update);
            }

        }

        if(StringUtils.isBlank(priority)){
            toWebSuccessJson(response);
        }else {
            toWebFailureJson(response,priority);
        }
    }

    //删除
    @RequestMapping({"/delete/{id}"})
    public void delete(@PathVariable Long id,
        HttpServletRequest request, HttpServletResponse response) {
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanDelete()){
            toWebFailureJson(response,"权限不足");
            return;
        }
        this.goodsService.deleteGoods(id);
        toWebSuccessJson(response);
    }
    //批量删除
    @RequestMapping({"/batchdelete/{ids}"})
    public void batchDelete(@PathVariable String ids, HttpServletRequest request,HttpServletResponse response) {
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanDelete()){
            toWebFailureJson(response,"权限不足");
            return;
        }
        if(StringUtils.isNotBlank(ids)){
            String[] idArr = ids.split(",");
            List<Long> list = new ArrayList<Long>();
            for(String id:idArr){
                if(StringUtils.isNotBlank(id)){
                    list.add(Long.valueOf(id));
                }
            }
            if(ListUtils.isNotBlank(list)){
                this.goodsService.batchDeleteGoods(list);
                toWebSuccessJson(response);
            }
        }else{
            toWebFailureJson(response,"没有要删除的主键");
        }
    }
    //清空表结构
    @RequestMapping(value = "truncate")
    public void truncate(HttpServletRequest request,HttpServletResponse response) {
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanTruncate()){
            toWebFailureJson(response,"权限不足");
            return;
        }
        this.goodsService.truncateGoods();
        toWebSuccessJson(response);
    }
    //json文件导入数据
    @RequestMapping(value = "import/json")
    public void importJson(@RequestParam MultipartFile myfiles,HttpServletRequest request,HttpServletResponse response) throws IOException {
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanImport()){
            toWebFailureJson(response,"权限不足");
            return;
        }
        if(myfiles.getOriginalFilename().endsWith(".txt") ||
            myfiles.getOriginalFilename().endsWith(".js")||
            myfiles.getOriginalFilename().endsWith(".json")){
            String fileContent = FileHelper.fastReadFileUTF8(myfiles.getInputStream());
            List<Goods> list = SerializerFastJsonUtil.get().readJsonList(fileContent,Goods.class);
            if(ListUtils.isNotBlank(list)){
                this.goodsService.transactionImportJsonList(list);
            }
            toWebSuccessJson(response);
        }else {
            toWebFailureJson(response, "不支持的文件后缀");
        }
    }
    //json文件导出
    @RequestMapping(value = "export/{exportFile}/{start}/{limit}",method = RequestMethod.GET)
    public void exportJson(@PathVariable String exportFile,@PathVariable Integer start,@PathVariable Integer limit,
        @RequestParam(required=false, value="orderBySqlField") String orderBySqlField,
        @RequestParam(required=false, value="descAsc") String descAsc,
        @RequestParam(required = false,value ="goodsNameFirst")                        String goodsNameFirst ,
        @RequestParam(required = false,value ="createTimeFirst")                    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date createTimeFirst ,
        @RequestParam(required = false,value ="createTimeSecond")                    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")Date createTimeSecond ,
        @RequestParam(required = false,value ="publisStatusFirst")                        Boolean publisStatusFirst ,
        HttpServletRequest request,HttpServletResponse response){
        Priority adminQueryPriority = AdminUserContextUtil.priority(request, moduleName);
        if(adminQueryPriority==null || !adminQueryPriority.getCanExport()){
            toWebFailureJson(response,"权限不足");
            return;
        }
        String orderBySqlFieldStr = ",id,goods_name,create_time,publis_status,";
        String orderBy = ProjectUtil.filterOrderBy(orderBySqlFieldStr,orderBySqlField,descAsc);
        Map<String,Object> query = ProjectUtil.buildMap("orderBy", orderBy, new Object[] {
                "goodsNameFirst",goodsNameFirst ,
                "createTimeFirst",createTimeFirst ,
                "createTimeSecond",createTimeSecond ,
                "publisStatusFirst",publisStatusFirst ,
        "limitIndex",start,"limit", limit });

        boolean useRelateQuery = false;
        List pageList;
            pageList = this.goodsService.getGoodsList(query);

        String file = moduleName;
        File tmpFile = null;
        try {
            if("excel".equals(exportFile)){
                tmpFile = File.createTempFile(file,".xlsx");
                POIUtil.writeExcelToTempFile(pageList,new String[]{ "主键", "商品名", "创建时间", "发布状态"},tmpFile);
            }else {
                tmpFile = File.createTempFile(file,".json");
                String json = JSON.toJSONString(pageList, true);
                FileHelper.fastWriteFileUTF8(tmpFile, json);
            }
            toFile(response, tmpFile);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(tmpFile!=null){
                tmpFile.delete();
            }
        }
    }


//===================搜索下拉框 外键查询使用begin=================================
    @RequestMapping(value = "type_ahead_search",method = RequestMethod.GET)
    public void typeAheadSearch(@RequestParam(value = "keyword",required = false) String keyword,
        @RequestParam(value = "foreignJavaField",required = false) String foreignJavaField,
        @RequestParam(value = "selectValue",required = false) String selectValue,
        HttpServletResponse response){
        if(StringUtils.isBlank(selectValue)){
            selectValue = selectValue();
        }
        List<Goods> list = goodsService.tryQueryList(keyword,selectValue,foreignJavaField);
        toSimpleJson(response,ProjectUtil.showList(list,selectValue,foreignJavaField));
    }

    private String selectValue(){
        StringBuffer sb = new StringBuffer();
                        sb.append("goodsName").append(",");
        return StringUtils.deleteLastChar(sb.toString());
    }

    //searchMapListJson [{"字段名":字段值},{"字段名":字段值}]
    @RequestMapping(value = "batch_search_type_ahead",method = RequestMethod.GET)
    public void batchSearchForTypeAhead(@RequestParam String searchMapListJson,HttpServletResponse response){
        List<Map<String,Object>> list = (List<Map<String,Object>>)JSON.parse(searchMapListJson);
        List<Goods> returnList = new ArrayList<Goods>();
        if(ListUtils.isNotBlank(list)){
            Map<String,Boolean> existMap = new HashMap<String,Boolean>();
            for(Map<String,Object> mapDto:list){
                Set<String> keys = mapDto.keySet();
                String key = null;
                Object value = null;
                for(String k:keys){
                    key = k;
                    value = mapDto.get(k);
                }
                if(key!=null && value!=null){
                    if(!existMap.containsKey(value+"")){//不要重复查询
                        existMap.put(value+"",true);
                        List<Goods> entityList = goodsService.getGoodsList(ProjectUtil.buildMap(key,value));
                        if(ListUtils.isNotBlank(entityList)){
                            returnList.addAll(entityList);
                        }
                    }
                }
            }
        }
        Map<String,Goods> returnMap = new HashMap<String,Goods>();
        if(ListUtils.isNotBlank(returnList)){
            for(Goods entity:returnList){
                returnMap.put(entity.getId()+"",entity);
            }
        }

        toWebSuccessJson(response,ProjectUtil.buildMap("foreignTableName","goods","selectValue",selectValue(),"returnMap",returnMap));
    }
    //===================end=================================

}
